#include <AT91SAM7S256.h>

#define AT91C_ADC_PRESCAL_SHIFT 8

#define AT91C_ADC_STARTUP_SHIFT 16


void ADC_Setup(void)
{ 
	
	AT91C_BASE_PMC->PMC_PCER |= 1 << 4;
	
	AT91C_BASE_ADC->ADC_CR = AT91C_ADC_SWRST;					// Software reset
	AT91C_BASE_ADC->ADC_MR =  AT91C_ADC_TRGEN_DIS |			// Disable hardware trigger
					AT91C_ADC_LOWRES_10_BIT |		// 10 bit precision
					AT91C_ADC_SLEEP_NORMAL_MODE |	// Normal mode
					5 << AT91C_ADC_PRESCAL_SHIFT|
					11<< AT91C_ADC_STARTUP_SHIFT;
					// TODO cuadrar clock
	//AT91C_BASE_ADC->ADC_CHER = 	AT91C_ADC_CH4 |				// Enable channel 4
	//					AT91C_ADC_CH5;				// Enable channel 5
	AT91C_BASE_ADC->ADC_CHDR = 	AT91C_ADC_CH0 |
						AT91C_ADC_CH1 |
						AT91C_ADC_CH2 |
						AT91C_ADC_CH3 |
						AT91C_ADC_CH6 |
						AT91C_ADC_CH7;
	AT91C_BASE_ADC->ADC_IDR = 	AT91C_ADC_EOC0 |			// Disable all interrupts
						AT91C_ADC_EOC1 |
						AT91C_ADC_EOC2 |
						AT91C_ADC_EOC3 |
						AT91C_ADC_EOC4 |
						AT91C_ADC_EOC5 |
						AT91C_ADC_EOC6 |
						AT91C_ADC_EOC7 |
						AT91C_ADC_OVRE0 |						
						AT91C_ADC_OVRE1 |
						AT91C_ADC_OVRE2 |
						AT91C_ADC_OVRE3 |
						AT91C_ADC_OVRE4 |
						AT91C_ADC_OVRE5 |
						AT91C_ADC_OVRE6 |
						AT91C_ADC_OVRE7 |
						AT91C_ADC_DRDY |
						AT91C_ADC_GOVRE |						
						AT91C_ADC_ENDRX |
						AT91C_ADC_RXBUFF;
						
}

short ADC_LeerDato(char canal)
{
	short dato=0;
			// Inicia la conversion
	//AT91C_BASE_ADC->ADC_CR 	= 	0x01;		// Inicia la conversion	
	if (canal == 4){
		AT91C_BASE_ADC->ADC_CHER = 	AT91C_ADC_CH4;

		AT91C_BASE_ADC->ADC_CR 	= 	AT91C_ADC_START;


		while (!(AT91C_BASE_ADC->ADC_SR & AT91C_ADC_EOC4));
		
		dato = AT91C_BASE_ADC->ADC_LCDR & AT91C_ADC_DATA;
		AT91C_BASE_ADC->ADC_CHDR = 	AT91C_ADC_CH4;			
	}
	else if (canal == 5){
		AT91C_BASE_ADC->ADC_CHER = 	AT91C_ADC_CH5;
		
		AT91C_BASE_ADC->ADC_CR 	= 	AT91C_ADC_START;

		while (!(AT91C_BASE_ADC->ADC_SR & AT91C_ADC_EOC5));
			
		dato = AT91C_BASE_ADC->ADC_LCDR & AT91C_ADC_DATA;
		AT91C_BASE_ADC->ADC_CHDR = 	AT91C_ADC_CH5;
	}

	return dato;				// Garantizar que siempre se retorna algo

}
